package com.qiangesoft.voice2text.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.qiangesoft.voice2text.constant.AliyunConstant;
import com.qiangesoft.voice2text.service.Voice2TextService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.regex.Matcher;

/**
 * 语音转文字
 *
 * @author qiangesoft
 * @date 2024-04-11
 */
@RequiredArgsConstructor
@RequestMapping("/filetrans/callback")
@RestController
public class FiletransController {

    private final Voice2TextService voice2TextService;

    @GetMapping(value = "/convert")
    public JSONArray convert() {
        String fileUrl = "https://gw.alipayobjects.com/os/bmw-prod/0574ee2e-f494-45a5-820f-63aee583045a.wav";
        return voice2TextService.convert(fileUrl);
    }

    @PostMapping(value = "/result")
    public void GetResult(@RequestBody String body) {
        try {
            // 获取JSON格式的文件识别结果
            String result = body;
            JSONObject jsonResult = JSONObject.parseObject(result);
            String statusCode = jsonResult.getString("StatusCode");
            Matcher matcherClient = AliyunConstant.PATTERN_CLIENT_ERR.matcher(statusCode);
            Matcher matcherServer = AliyunConstant.PATTERN_SERVER_ERR.matcher(statusCode);
            // 以2开头状态码为正常状态码，回调方式正常状态只返回“21050000”
            if ("21050000".equals(statusCode)) {
                JSONArray jsonArray = jsonResult.getJSONObject(AliyunConstant.KEY_RESULT).getJSONArray("Sentences");
                for (int i = 0; i < jsonArray.size(); i++) {
                    System.out.println(jsonArray.get(i));
                }
            } else if (matcherClient.matches()) {
                System.out.println("状态码以4开头表示客户端错误......");
            } else if (matcherServer.matches()) {
                System.out.println("状态码以5开头表示服务端错误......");
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}